package cn.lanqiao.book.controller;


import cn.lanqiao.book.pojo.User;
import cn.lanqiao.book.service.impl.UserServiceImpl;

import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;

/*
 * 用于处理注册请求
 * 处理表单中的数据，生成一条用户记录插入到数据库
 * 注册成功则跳转到首页
 * 注册失败则重新回到注册页面，并返回一个 错误信息 msg
 * */
@WebServlet("/register")
public class Register extends HttpServlet {
    @Override
    protected void doPost(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
        User userBean = getUser(req);
        resp.setCharacterEncoding("UTF-8");
        if (!UserServiceImpl.getInstance().register(userBean)) {
            req.setAttribute("msg", "注册失败!");
            req.getRequestDispatcher("/register.jsp").forward(req, resp);
        } else {
            req.getRequestDispatcher("/index.jsp").forward(req, resp);
        }
    }

    @Override
    protected void doGet(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
        doPost(req, resp);
    }

    private User getUser(HttpServletRequest request) {
        User user;
        String username = request.getParameter("username");
        String password = request.getParameter("password");
        String email = request.getParameter("email");
        Integer sex = Integer.valueOf(request.getParameter("sex"));
        String qq = request.getParameter("qq");
        if (qq == "") {
            qq=null;
        }
        String web = request.getParameter("web");
        user = new User(username, password, email, sex, qq, web);
        return user;
    }
}
